package com.novellotus.iov.carvice.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ljd.retrofit.progress.ProgressHelper;
import com.novellotus.httploadingview.LoadingView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.bean.MqttListCarBean;
import com.novellotus.iov.carvice.bean.MqttSingleCarStatue;
import com.novellotus.iov.carvice.bean.MqttVehicleBean;
import com.novellotus.iov.carvice.bean.RxCarListBean;
import com.novellotus.iov.carvice.bean.RxUpdate;
import com.novellotus.iov.carvice.fragment.CarListFragment;
import com.novellotus.iov.carvice.fragment.CarViewpagerFragment;
import com.novellotus.iov.carvice.fragment.EmptyFragment;
import com.novellotus.iov.carvice.model.MainActivityModel;
import com.novellotus.iov.carvice.model.MainModel;
import com.novellotus.iov.carvice.model.MqttModule;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.HandlerUtils;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.SharedPreferencesUtils;
import com.novellotus.iov.carvice.view.TipsDialog;
import com.tbruyelle.rxpermissions2.Permission;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 旧的APP主页面
 * */
public class MainActivityOld extends BaseActivity implements LoadingView.OnBtnClickListener, CarViewpagerFragment.CarSwitchInterface, MqttModule.MqttMessageInterface, DrawerLayout.DrawerListener, MainModel.MainModelInterface, TipsDialog.ClickTipsInterface, HandlerUtils.OnReceiveMessageListener {

    @BindView(R.id.btn_personal)
    ImageView btnPersonal;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.tv_plate)
    TextView tv_plate;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.btn_map)
    ImageView btn_map;
    @BindView(R.id.tv_count)
    TextView tv_count;
    @BindView(R.id.ln_drawer)
    RelativeLayout ln_drawer;
    @BindView(R.id.tv_update_tips)
    TextView tv_update_tips;
    @BindView(R.id.img_tips)
    ImageView img_tips;
    @BindView(R.id.loadingView)
    LoadingView loadingView;
    @BindView(R.id.tv_modify_phone)
    TextView tv_modify_phone;

    private EmptyFragment emptyFragment;
    private CarListFragment carListFragment;
    private CarViewpagerFragment carViewpagerFragment;
    private String[] key;
    private MqttModule mqttModule;
    private MainModel mainModel;
    private final int MAX_VIEWPAGER_COUNT = 5;
    private boolean isUpdate = false;
    private boolean isFirstTime = true;
    private HandlerUtils.HandlerHolder handlerHolder;

    private int fragmentType = 0;//0 empty   1 viewpager 2 list

    @Override
    protected void initContentView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main_old);
    }

    @Override
    public void init() {
        handlerHolder = new HandlerUtils.HandlerHolder(this);
        key = SharedPreferencesUtils.getKey(this);

        mqttModule = new MqttModule(this, this, key[0], key[1]);
        mainModel = new MainModel(this, this);
        mainModel.checkUpdate();
        MainActivityModel mainActivityModel = new MainActivityModel(this);
        mainActivityModel.initImage(image);
        mainModel.setMapButton(btn_map);
        drawerLayout.addDrawerListener(this);
        loadingView.setLoadingModel(LoadingView.MODEL_DEFAULT);
        loadingView.setOnBtnClickListener(this);

        //4.4系统下移一个状态栏高度
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            RelativeLayout mDrawerLayout = findViewById(R.id.rlt_main);
            RelativeLayout ln_drawer = findViewById(R.id.ln_drawer);
            mDrawerLayout.setPadding(0, MyUtils.getStatusBarHeight(getApplicationContext()), 0, 0);
            ln_drawer.setPadding(0, MyUtils.getStatusBarHeight(getApplicationContext()), 0, 0);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        tv_name.setText(SharedPreferencesUtils.getUser(this)[0]);

        if (drawerLayout != null) {
            mainModel.updateMessageCount();
        }
        if (mainModel != null) {
            mainModel.getList(1);
        }
    }


    /**
     * 根据最新获取的车辆数量改变布局
     */
    public void replaceFragment(int type, RxCarListBean response) {

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        switch (type) {
            case 0:
                tv_plate.setText("");
                btn_map.setVisibility(View.INVISIBLE);
                emptyFragment = new EmptyFragment();
                fragmentTransaction.replace(R.id.content, emptyFragment);
                fragmentType = 0;
                break;
            case 1:
                btn_map.setVisibility(View.VISIBLE);
                if (fragmentType != 1) {
                    carViewpagerFragment = new CarViewpagerFragment();
                    carViewpagerFragment.initFragment(response.getRecords());
                    fragmentTransaction.replace(R.id.content, carViewpagerFragment);
                } else {
                    carViewpagerFragment.updateViewpager(response.getRecords());
                }

                fragmentType = 1;
                break;
            case 2:
                btn_map.setVisibility(View.VISIBLE);
                tv_plate.setText("车辆列表  (" + response.getTotal() + ")");
                if (fragmentType != 2) {
                    carListFragment = new CarListFragment();
                    carListFragment.initList(response);
                    MyUtils.logInformation("替换CarListFragment");
                    fragmentTransaction.replace(R.id.content, carListFragment);
                } else {
                    carListFragment.updateList();
                }
                fragmentType = 2;
                break;
        }
        fragmentTransaction.commit();
    }


    @OnClick(R.id.btn_personal)
    void openDrawer() {
        drawerLayout.openDrawer(GravityCompat.START);
    }


    @OnClick(R.id.btn_add)
    void addCar() {
        openForResultActivity(AttentionActivity.class);
    }


    /**
     * mqtt刷新
     * 刷新当前数据
     */
    MqttVehicleBean mqttVehicleBean;
    String vin;
    long mqttVehicleBeanTime;

    void update(MqttListCarBean mqttListCarBean, MqttVehicleBean mqttVehicleBean, String vin) {
        if (fragmentType == 1) {
            //刷新页面数据
            this.mqttVehicleBean = mqttVehicleBean;
            mqttVehicleBeanTime = System.currentTimeMillis();
            this.vin = vin;
            //如果收到的单车数据比车辆状态主题晚，而且相差的时间在2秒内，则在这里刷新
            if (0 <= mqttVehicleBeanTime - mqttSingleCarStatueTime && mqttVehicleBeanTime - mqttSingleCarStatueTime < 10000) {
                if (mqttSingleCarStatue != null) {
                    int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
                    int carDetailType = MyUtils.carDetailType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
                    carViewpagerFragment.updateSinglePager(mqttVehicleBean, vin, carType, carDetailType);
                    //  carStatuesFragment.mqttUpdate(mqttVehicleBean, carType, carDetailType);
                }
            }

        } else if (fragmentType == 2) {
            //刷新列表数据
            carListFragment.updateSingleCar(mqttListCarBean);
        }
    }

    @OnClick(R.id.rlt_personal)
    void openPerson() {
        openActivity(PersonalActivity.class);
    }

    @OnClick(R.id.rlt_message)
    void openMessage() {
        openActivity(MessageActivity.class);
    }

    @OnClick(R.id.rlt_about)
    void openAbout() {
        if (des.length() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString("des", des);
            bundle.putString("url", url);
            openActivity(AboutActivity.class, bundle);
        } else {
            openActivity(AboutActivity.class);
        }

    }

    @OnClick(R.id.rlt_record)
    void openTask() {
        openActivity(TaskActivity.class);
    }

    @OnClick(R.id.rlt_modify_password)
    void openPassword() {
        openActivity(ModifyPasswordActivity.class);
    }

    @OnClick(R.id.rlt_modify_phone)
    void openPhone() {
        openActivity(ModifyMobileActivity.class);
    }

    @OnClick(R.id.rlt_out_login)
    void outLogin() {
        openActivity(LoginActivity.class);
        SharedPreferencesUtils.deleteSharedPreferences(this);
        finish();
    }


    @Override
    public void ChangePlate(String s) {
        tv_plate.setText(s);
    }

    /**
     * 取消关注车辆后刷新数据
     */
    @Override
    public void UpdateCar() {
        mainModel.getList(1);
    }


    @Override
    public void getTopic(MqttListCarBean mqttListCarBean, MqttVehicleBean mqttVehicleBean, String vin) {
        if (mqttListCarBean != null || mqttVehicleBean != null) {
            update(mqttListCarBean, mqttVehicleBean, vin);
        }
    }


    MqttSingleCarStatue mqttSingleCarStatue;
    long mqttSingleCarStatueTime;

    @Override
    public void getSingleCarStatue(MqttSingleCarStatue mqttSingleCarStatue) {
        this.mqttSingleCarStatue = mqttSingleCarStatue;
        mqttSingleCarStatueTime = System.currentTimeMillis();
        //如果收到的车辆状态比单车数据主题早，而且相差的时间在2秒内，则在这里刷新
        if (0 <= mqttSingleCarStatueTime - mqttVehicleBeanTime && mqttSingleCarStatueTime - mqttVehicleBeanTime < 10000) {
            int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            int carDetailType = MyUtils.carDetailType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            if (mqttVehicleBean != null) {
                carViewpagerFragment.updateSinglePager(mqttVehicleBean, vin, carType, carDetailType);
            }
        } else if (mqttSingleCarStatue != null) {
            int carType = MyUtils.carType(mqttSingleCarStatue.getOnlineStatus(), mqttSingleCarStatue.getChargeStatus(), mqttSingleCarStatue.getAlarmStatus());
            if (carType == 0 && mqttVehicleBean != null) {
                carViewpagerFragment.updateSinglePager(mqttVehicleBean, vin, 0, 0);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 101) {
            if (data != null && data.getBooleanExtra("isUpdate", false)) {

            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (mqttModule != null) {
            mqttModule.startReconnect();
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mqttModule != null) {
            mqttModule.closeMqtt();
        }

    }

    @Override
    public void onDrawerSlide(View drawerView, float slideOffset) {

    }

    @Override
    public void onDrawerOpened(View drawerView) {
        if (SharedPreferencesUtils.getUser(this)[1].equals("") || SharedPreferencesUtils.getUser(this)[0].length() == 0) {
            tv_modify_phone.setText("绑定手机");
        } else {
            tv_modify_phone.setText("修改手机");
        }
        drawerView.setClickable(true);
    }


    @Override
    public void onDrawerClosed(View drawerView) {

    }

    @Override
    public void onDrawerStateChanged(int newState) {

    }

    @Override
    public void getCarList(RxCarListBean response) {
        isFirstTime = false;
        loadingView.success();
        if (response.getRecords().size() == 0) {
            //显示提示关注布局
            replaceFragment(0, response);
        } else if (response.getRecords().size() <= MAX_VIEWPAGER_COUNT) {
            //显示Viewpager
            replaceFragment(1, response);
        } else {
            //显示车辆列表
            replaceFragment(2, response);
        }
        //设置mqtt订阅主题
        if (response.getRecords().size() != 0) {
            mqttModule.stopConnect();
            setTopic(response);
        }
    }

    @Override
    public void getCarListFail(String msg) {
        if (isFirstTime) {
            loadingView.empty(msg, true);
        }

    }

    /**
     * @param response 根据关注的车辆订阅mqtt主题
     */
    private void setTopic(RxCarListBean response) {
        //      String[] topic = new String[]{"$NL/ne/evbus/" + key[2] + "/follow_vehicles/" + vin, "$NL/ne/evbus/" + key[2] + "/real_time_info/" + vin};
        String topic[];
        if (response.getRecords().size() <= MAX_VIEWPAGER_COUNT) {
            int size = response.getRecords().size();
            int doubleSize = size * 2;
            topic = new String[doubleSize];
            //   MyUtils.logInformation("topic:" + topic.length);
            for (int i = 0; i < doubleSize; i++) {
                if (i < size) {
                    topic[i] = "$NL/ne/evbus/" + key[2] + "/real_time_info/" + response.getRecords().get(i).getVin();
                } else {
                    topic[i] = "$NL/ne/evbus/" + key[2] + "/follow_vehicles/" + response.getRecords().get(i - size).getVin();
                }
            }
        } else {
            topic = new String[]{"$NL/ne/evbus/" + key[2] + "/follow_vehicles"};
        }
        mqttModule.setTop(topic, response.getRecords().size() <= MAX_VIEWPAGER_COUNT ? 2 : 0);
        mqttModule.startReconnect();
    }

    @Override
    public void getMessageCount(int count) {
        if (count > 0) {
            tv_count.setText(count + "");
            tv_count.setVisibility(View.VISIBLE);
            img_tips.setVisibility(View.VISIBLE);
        } else {
            tv_count.setVisibility(View.GONE);
            img_tips.setVisibility(View.INVISIBLE);
        }
    }

    String des = "", url = "";
    TipsDialog tipsDialog;

    @Override
    public void getUpdateMessage(RxUpdate response) {
        if (response.getUpdate() == 1 || response.getUpdate() == 2) {
            isUpdate = true;
            des = response.getAppVersionVO().getUpdateLog();
            url = response.getAppVersionVO().getDownloadUrl();
            tipsDialog = new TipsDialog(this);
            tipsDialog.initDialog("版本更新", des, this);
            tv_update_tips.setVisibility(View.VISIBLE);
            tv_update_tips.setText("NEW " + response.getAppVersionVO().getAppName());

            tipsDialog.button.setText("更新");
            if (response.getUpdate() == 1) {
                tipsDialog.setCancelable(false);
                tipsDialog.img_cancel.setVisibility(View.GONE);
            }
            tipsDialog.show();
        } else {
            tv_update_tips.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void clickTipsButton() {
        if (isUpdate) {
            Observable.create(new ObservableOnSubscribe<Object>() {
                @Override
                public void subscribe(ObservableEmitter<Object> e) throws Exception {
                    e.onNext(1);
                }
            })
                    .compose(RxSchedulers.lifecycle(this))
                    .compose(rxPermissions.ensureEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)).subscribe(new Consumer<Permission>() {
                @Override
                public void accept(Permission permission) throws Exception {
                    if (permission.granted) {
                        RetrofitFactory.getDownLoadInstance(MainActivityOld.this, "版本更新", des).downloadFile(url)
//                                .compose(RxSchedulers.<ResponseBody>lifecycle(MainActivity.this))
                                .subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe(new MyObserver<ResponseBody>() {
                            @Override
                            public void onNext(ResponseBody responseBody) {
                                super.onNext(responseBody);
                                ProgressHelper.outPutApk(responseBody.byteStream(), MainActivityOld.this);
                            }

                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                Message message = new Message();
                                message.what = 0;
                                message.obj = e.toString();
                                handlerHolder.sendMessage(message);
                            }
                        });
                    } else {
                        MyUtils.showToast(MainActivityOld.this, "读写手机存储权限被禁止，请在设置中允许相关权限");
                    }
                }
            });
        }
        tipsDialog.dismiss();
    }


    private long firstTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        long secondTime = System.currentTimeMillis();
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (secondTime - firstTime < 2000) {
                System.exit(0);
            } else {
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onReload() {
        mainModel.getList(1);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mqttModule.destroyModule();
    }

    @Override
    public void handlerMessage(Message msg) {
        MyUtils.showToast(MainActivityOld.this, msg.obj.toString());
    }
}
